﻿//'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
    startSearchEngine();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}


function startSearchEngine() {
    $('#txtSearchBox').keyup(txtSearchBox_KeyUp);
}

function txtSearchBox_KeyUp(args) {
    if ($("#txtSearchBox").val().length == 0)
        $("#pnlSearchResult").html('');
    else
        executeSearch();
}
function executeSearch() {
    var query = encodeURIComponent( $("#txtSearchBox").val());

    SPSearchResults =
    {
        element: '',
        url: '',

        init: function (element) {
            SPSearchResults.element = element;
            SPSearchResults.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + query + "*'";
        },

        load: function () {
            $.ajax(
                {
                    url: SPSearchResults.url,
                    method: "GET",
                    headers:
                    {
                        "accept": "application/json;odata=verbose",
                    },
                    success: SPSearchResults.onSuccess,
                    error: SPSearchResults.onError
                }
            );
        },

        onSuccess: function (data) {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

            var html = "<div class='results'>";
            for (var i = 0; i < results.length; i++) {
                var d = new Date(results[i].Cells.results[8].Value);
                var currentDate = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();

                html += "<div class='result-row' style='padding-bottom:5px; border-bottom: 1px solid #c0c0c0;'>";
                var clickableLink = "<a href='" + results[i].Cells.results[6].Value + "'>" + results[i].Cells.results[3].Value + "</a><br/><span>Type: " + results[i].Cells.results[17].Value + "</span><br/><span>Modified: " + currentDate + "</span>";
                html += clickableLink;
                html += "</div>";
            }

            html += "</div>";
            $("#pnlSearchResult").html(html);
        },

        onError: function (err) {
            $("#pnlSearchResult").html("<h3>An error occured</h3><br/>" + JSON.stringify(err));
        }
    };

    // Call our Init-function
    SPSearchResults.init($('#pnlSearchResult'));

    // Call our Load-function which will post the actual query
    SPSearchResults.load();
}
